package com.xmy.cultivate.controller;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkl.laop.sdk.exception.SDKException;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.constants.CommonConstant;
import com.xmy.cultivate.constants.MqConstants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.BackOrderApply;
import com.xmy.cultivate.entity.views.GradePositionRequest;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.SourseLeveEnum;
import com.xmy.cultivate.enums.StatusOrderApplyEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.respons.LklPay;
import com.xmy.cultivate.respons.OrderApplyMoreRs;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单报名信息 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-28
 */
@RestController
@RequestMapping("/api/apply")
@Scope("prototype")
public class OrderApplyController extends BaseController {
    @Autowired
    ICourseService iCourseService;
    @Autowired
    IOrderApplyService iOrderApplyService;
    @Autowired
    IGradeService iGradeService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IRenewDataService iRenewDataService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IOrderTransferService iOrderTransferService;

    @Autowired
    IOrderTransferDetailService iOrderTransferDetailService;

    @Autowired
    IRecordCostService iRecordCostService;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IStudentService studentService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IOrderApplyAffirmService iOrderApplyAffirmService;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IOrderDisPriceService iOrderDisPriceService;

    @Autowired
    @Lazy
    IStudentClassTypeService iStudentClassTypeService;

    @Autowired
    @Lazy
    ICisPositionService iCisPositionService;

    @Autowired
    @Lazy
    IEnrollSetService iEnrollSetService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    IStudentReadSchoolService iStudentReadSchoolService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    ILklPayService iLklPayService;

    @Autowired
    ILklMerchantService iLklMerchantService;

    @Autowired
    ILklOrderService iLklOrderService;

    @Autowired
    ILklMerchantSetService iLklMerchantSetService;

    @Autowired
    IWecharsBindService iWecharsBindService;

    @Value("${lkl.notifyUrl}")
    String notifyUrl;

    @GetMapping()
    public Result findAll(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                          @RequestParam(value = "yearPart", defaultValue = "", required = false) String yearPart,
                          @RequestParam(value = "quarterNum", defaultValue = "", required = false) String quarterNum,
                          @RequestParam(value = "startDate", defaultValue = "", required = false) String startDate,
                          @RequestParam(value = "endDate", defaultValue = "", required = false) String endDate,
                          @RequestParam(value = "orderType", defaultValue = "", required = false) String orderType,
                          @RequestParam(value = "isOwn", defaultValue = "", required = false) String isOwn,
                          @RequestParam(value = "status", defaultValue = "", required = false) String status,
                          @RequestParam(value = "keyType", defaultValue = "", required = false) String keyType,
                          @RequestParam(value = "keyWord", defaultValue = "", required = false) String keyWord,
                          @RequestParam(value = "subjectsId", defaultValue = "", required = false) String subjectsId,
                          @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                          @RequestParam(value = "payTypeList", defaultValue = "") String[] payTypeList,
                          @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                          @RequestParam(value = "lessonType", defaultValue = "", required = false) String lessonType) throws InterruptedException {

        IPage<OrderApply> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<OrderApply> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
            queryWrapper.between("handle_date", startDate, endDate);
        }
        queryWrapper.eq(StringUtils.isNotBlank(isOwn), "is_own", isOwn);

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
//        queryWrapper.eq(StringUtils.isNotBlank(orderType),"order_type",orderType);

        if (StringUtils.isNotBlank(orderType)) {
            String orderType1 = "";
            String[] orderTypes = orderType.split(",");
            for (String type : orderTypes) {
                if (StringUtils.isNotBlank(type)) {
                    if ("4".equals(type)) {
                        orderType1 += "(order_type = 4 AND (apply_type <> 5 OR apply_type IS NULL )) OR ";
                    }
                    if ("6".equals(type)) {
                        orderType1 += "(order_type = 4 AND apply_type = 5) OR ";
                    }
                    if (!"6".equals(type) && !"4".equals(type)) {
                        orderType1 += "(order_type = " + type + ") OR ";
                    }
                }
            }

            // 去除末尾的"OR"和空格
            if (orderType1.endsWith("OR ")) {
                orderType1 = orderType1.substring(0, orderType1.length() - 4);
            }
            String finalOrderType = orderType1;
            queryWrapper.and(wrapper -> wrapper.apply(finalOrderType));
        }

        if (schoolIdList.length > 0) {
            queryWrapper.in("handle_school_id", schoolIdList);
        } else {
            queryWrapper.in("handle_school_id", this.baseSchoolIdList);
        }

        if (payTypeList.length > 0) {
            String typeStr = String.join(",", payTypeList);
            queryWrapper.inSql("id", "select order_id from order_pay_account where accoun_type in (" + typeStr + ")");
        }

        if (this.sourseLeveEnum.equals(SourseLeveEnum.ONESELF)) {
            queryWrapper.eq("created_id", this.adminId);
        }

        if (keyType.equals("1") && StringUtils.isNotBlank(keyWord)) {
            // 学员姓名
            queryWrapper.like("student_name", keyWord);
        } else if (keyType.equals("2") && StringUtils.isNotBlank(keyWord)) {
            // 订单号
            queryWrapper.eq("id", keyWord);
        } else if (keyType.equals("3") && StringUtils.isNotBlank(keyWord)) {
            // 课程名称
            queryWrapper.inSql("id", "select course_id from order_detail where course_name like('%" + keyWord + "%')");
        } else if (keyType.equals("4") && StringUtils.isNotBlank(keyWord)) {
            // 手机号
            queryWrapper.eq("linkman_phone", keyWord);
        } else if (keyType.equals("5") && StringUtils.isNotBlank(keyWord)) {
            // 身份证号
            queryWrapper.eq("id_card_no", keyWord);
        }
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("created_at");
        orderBy.add("id");
        queryWrapper.orderByDesc(orderBy);
        queryWrapper.eq("deleted", 0);
        if (StringUtils.isNotBlank(subjectsId)) {
            //queryWrapper.and(i -> i.inSql("id", "select order_id from order_detail where subjects_id =" + subjectsId + "").or().inSql("id", "select a.order_id from order_transfer_detail as a LEFT JOIN order_detail as b on a.old_order_detail_id = b.id where b.subjects_id=" + subjectsId + ""));
            queryWrapper.eq("subjects_id_str", subjectsId);
        }
        //只查看已支付的
        queryWrapper.and(i -> i.eq("sign_type", 1).or(j -> j.eq("sign_type", 3).eq("pay_type", 1)));
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);

        iOrderApplyService.findAll(iPage, queryWrapper);

        queryWrapper.eq("abolish_type",1);
        OrderApply orderApply = iOrderApplyService.getOrderApplySum(queryWrapper);

        HashMap hashMap = new HashMap<>();
        if (orderApply != null) {
            hashMap.put("priceSum", orderApply.getPrice());
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages(), hashMap));
    }

    @GetMapping("getPrintDate")
    public Result getPrintData(@RequestParam(name = "orderId", required = true) Long orderId) {
        OrderApply orderApply = iOrderApplyService.getPrintData(orderId);
        return new Result(Code.OK, orderApply, "");
    }

    @PostMapping("getPrintDateMore")
    public Result getPrintDateMore(@RequestBody Map reMap) {
        List<String> orderIdList = (List<String>) reMap.get("orderIdList");
        List<OrderApply> orderApplies = new ArrayList<>();
        for (String orderId : orderIdList) {
            OrderApply orderApply = iOrderApplyService.getPrintData(Long.valueOf(orderId));
            orderApplies.add(orderApply);
        }
        return new Result(Code.OK, orderApplies, "");
    }


    /**
     * 获取退费订单
     *
     * @param reMap
     * @return
     * @throws InterruptedException
     */
    @GetMapping("backOrderApply")
    public Result backOrderApply(@RequestParam Map<String, String> reMap) throws InterruptedException {
        String schoolId = reMap.get("schoolId");
        String subjectsId = reMap.get("subjectsId");
        String studentId = reMap.get("studentId");
        String quarterNum = reMap.get("quarterNum");
        String yearPart = reMap.get("yearPart");

        if (StringUtils.isBlank(schoolId)) {
            return new Result(Code.ERROR, "", "请选择校区");
        }
        if (StringUtils.isBlank(subjectsId)) {
            return new Result(Code.ERROR, "", "请选择科目");
        }
        if (StringUtils.isBlank(studentId)) {
            return new Result(Code.ERROR, "", "请选择学生");
        }
        if (StringUtils.isBlank(quarterNum)) {
            return new Result(Code.ERROR, "", "请选择学期");
        }
        if (StringUtils.isBlank(yearPart)) {
            return new Result(Code.ERROR, "", "请选择年份");
        }

        QueryWrapper<OrderApply> orderApplyQueryWrapper = new QueryWrapper<>();
        //orderApplyQueryWrapper.eq("school_id",schoolId);
        //orderApplyQueryWrapper.eq("order_type",4);
        orderApplyQueryWrapper.ne("status", 2);
        orderApplyQueryWrapper.in("order_type", 4);
        //orderApplyQueryWrapper.inSql("id","select order_id from order_transfer_detail where school_id = "+schoolId+" and subjects_id = "+subjectsId+" and year_part = "+yearPart+" and quarter_num = "+quarterNum+" and student_id = "+studentId);
        QueryWrapper<OrderTransferDetail> orderTransferDetailQueryWrapper = new QueryWrapper<>();
        orderTransferDetailQueryWrapper.eq("school_id", schoolId);
        orderTransferDetailQueryWrapper.eq("subjects_id", subjectsId);
        orderTransferDetailQueryWrapper.eq("year_part", yearPart);
        orderTransferDetailQueryWrapper.eq("quarter_num", quarterNum);
        orderTransferDetailQueryWrapper.eq("student_id", studentId);
        List<Long> orderIdList = iOrderTransferDetailService.getStudentIdListForWhere(orderTransferDetailQueryWrapper);
        if (orderIdList.size() == 0) {
            orderIdList.add(0L);//为空加默认值停止报错
        }
        orderApplyQueryWrapper.in("id", orderIdList);
        List<OrderApply> orderApplies = iOrderApplyService.list(orderApplyQueryWrapper);

        List<OrderTransferDetail> orderTransferDetailList = null;
        List<BackOrderApply> backOrderApplyList = new ArrayList<>();
        for (OrderApply orderApply : orderApplies) {
            BackOrderApply backOrderApply = new BackOrderApply();
            BeanUtils.copyProperties(orderApply, backOrderApply);

            backOrderApply.setYearPart(Integer.parseInt(yearPart));
            backOrderApply.setQuarterNum(Integer.parseInt(quarterNum));

            Student student = iStudentService.getById(orderApply.getStudentId());
            if (student != null) {
                backOrderApply.setStudentName(student.getName());
                backOrderApply.setLinkmanPhone(student.getLinkmanPhone());
            }

            orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id", orderApply.getId()));
            BigDecimal allPrice = new BigDecimal(0);
            for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
                OrderDetail orderDetailOld = iOrderDetailService.getOne(new QueryWrapper<OrderDetail>().eq("id", orderTransferDetail.getOldOrderDetailId()).eq("year_part", yearPart).eq("quarter_num", quarterNum));
                if (orderDetailOld == null) {
                    continue;
                }
                allPrice = allPrice.add(orderDetailOld.getOutPrice());
            }
            backOrderApply.setPrice(allPrice);
            backOrderApplyList.add(backOrderApply);
        }

        return new Result(Code.OK, new PageResult(backOrderApplyList, (long) backOrderApplyList.size(), 1L));
    }

    /**
     * 修改退费金额
     *
     * @param map
     * @return
     */
    @PostMapping("/backPriceUpdate")
    @Transactional
    public Result backPriceUpdate(@RequestBody Map<String, String> map) {

        Long orderIdOut = Long.parseLong(map.get("orderId"));//退费订单id
        BigDecimal outPricePrice = new BigDecimal(map.get("outPrice"));

        String quarterNum = map.get("quarterNum");
        String yearPart = map.get("yearPart");

        /**
         * 退费订单
         */
        OrderApply orderApply = iOrderApplyService.getById(orderIdOut);

        List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id", orderApply.getId()));
        BigDecimal allPrice = new BigDecimal(0);
        for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
            OrderDetail orderDetailOld = iOrderDetailService.getOne(new QueryWrapper<OrderDetail>().eq("id", orderTransferDetail.getOldOrderDetailId()).eq("year_part", yearPart).eq("quarter_num", quarterNum).ne("order_type", 3));
            if (orderDetailOld == null) {
                continue;
            }
            allPrice = allPrice.add(orderDetailOld.getOutPrice());
        }


        if (allPrice.compareTo(outPricePrice) <= 0) {
            return new Result(Code.ERROR, "", "退费金额不能大于或等于原来的金额");
        }
        OrderTransfer orderTransfer = iOrderTransferService.getOne(new QueryWrapper<OrderTransfer>().eq("order_id", orderIdOut));
        if (orderTransfer == null) {
            return new Result(Code.ERROR, "", "退费订单异常");
        }

        BigDecimal outPricePriceOld = orderApply.getPrice();
        BigDecimal diffPrice = allPrice.subtract(outPricePrice);//差额

        orderApply.setSolidPrice(orderApply.getSolidPrice().subtract(diffPrice));
        orderApply.setPrice(orderApply.getSolidPrice().subtract(diffPrice));
        String tradeContent = orderApply.getTradeContent();
        tradeContent = tradeContent.replace("应退学费" + outPricePriceOld, "应退学费" + outPricePriceOld.subtract(diffPrice));
        orderApply.setTradeContent(tradeContent);
        iOrderApplyService.updateById(orderApply);


        orderTransfer.setOutPrice(orderApply.getPrice());
        iOrderTransferService.updateById(orderTransfer);


        //List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(new QueryWrapper<OrderTransferDetail>().eq("order_id",orderIdOut));

        BigDecimal changeDiffPrice = diffPrice;
        for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
            if (changeDiffPrice.compareTo(BigDecimal.ZERO) > 0) {
                OrderDetail orderDetailOld = iOrderDetailService.getOne(new QueryWrapper<OrderDetail>().eq("id", orderTransferDetail.getOldOrderDetailId()).eq("year_part", yearPart).eq("quarter_num", quarterNum).ne("order_type", 3));//order_type!=3排除掉转课的
                if (orderDetailOld == null) {
                    continue;
                }
                BigDecimal newOutPrice = changeDiffPrice;
                if (orderDetailOld.getOutPrice().compareTo(changeDiffPrice) < 0) {
                    newOutPrice = orderDetailOld.getOutPrice();
                }
                changeDiffPrice = changeDiffPrice.subtract(newOutPrice);//还剩下x金额未减
                if (orderTransferDetail.getOrderType().equals(4)) {
                    //退费
                    orderDetailOld.setOutPrice(orderDetailOld.getOutPrice().subtract(newOutPrice));//修改原来订单的退费金额
                } else {
                    //退费
                    orderDetailOld.setOutPrice(orderDetailOld.getOutPrice().subtract(newOutPrice));//修改原来订单的退费金额
                    //转校退费,都是放在OutPrice，故注释掉
                    //orderDetailOld.setRollOutPrice(orderDetailOld.getRollOutPrice().subtract(newOutPrice));//修改原来订单的退费金额
                }
                orderTransferDetail.setOutPrice(orderTransferDetail.getOutPrice().subtract(newOutPrice));//修改订单记录的退费金额

                iOrderDetailService.updateById(orderDetailOld);
                iOrderTransferDetailService.updateById(orderTransferDetail);
                //处理异常金额
                iOrderApplyService.abnormalPriceDispose(orderDetailOld.getYearPart(), orderDetailOld.getQuarterNum(), orderDetailOld.getSchoolId(), orderDetailOld.getStudentId(), orderDetailOld.getSubjectsId(), orderDetailOld.getId(), newOutPrice);
            }
        }
        return new Result(Code.OK, "", "修改退费金额成功");
    }

    @RequiresPermissions(value = "manage:apply")
    @PostMapping()
    @RepeatSubmit(expireSeconds = 30)
    public Result save(@RequestBody OrderApply orderApply) throws Exception {

        Quarter quarterNow = iQuarterService.getNowQuarter();
        quarterNow.getNum();
        //生成拉卡拉订单号
        String lklOrderNo = "";
        if (orderApply.getSignType().equals(3)) {
            //生成拉卡拉订单号
            lklOrderNo = "KFPT" + CommonUtil.getLklOrderNo();//支付上线时打开
        }


//        Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
//        if (count > 0) {
//            //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
//        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            Integer receiptNo = CommonUtil.getReceiptNo();
            orderApply.setReceiptNo(receiptNo.toString());
        }
        Long orderId = idWorker.nextId();
        orderApply.setId(orderId);

        if (orderApply.getSignType().equals(3)) {
            orderApply.setStatus(StatusOrderApplyEnum.TOVOID);//设置为课时未生效//支付上线时打开
            orderApply.setLklOrderNo(lklOrderNo);//支付上线时打开
        }else {
            orderApply.setPayeeId(orderApply.getHandlePersonId());//设置收款人为经办人
        }

        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);
        List<String> stringList = new ArrayList<>();

        Long subjectsId = 0L;
        Long studentId = orderApply.getStudentId();
        Long applyCount = 0L;
        Integer yearClassId = 0;
        Course course = null;
        for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
            course = iCourseService.getById(orderDetail.getCourseId());
            yearClassId = course.getYearClassId().getKey();

            if (orderApply.getSignType().equals(3)) {
                orderDetail.setLklOrderNo(lklOrderNo);//支付上线时打开
                orderDetail.setStatus(StatusOrderApplyEnum.TOVOID);//设置为课时未生效//支付上线时打开
                //支付上线时打开
                orderDetail.setSignType(3);//支付上线时打开
            }
            //添加当前报读的续班信息
            Integer yearPart = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
            if (orderDetail.getGradeId() != null) {
                String clashStr = "";
                List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(yearPart, course.getQuarterNum(), orderDetail.getStudentId(), orderDetail.getGradeId(), nowDateTime.toString());
                if (repairCourseList.size() > 0) {
                    Student student = iStudentService.getById(orderDetail.getStudentId());
                    for (RepairCourse repairCourse : repairCourseList) {
                        clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                        stringList.add(clashStr);
                    }
                }
            }
            orderApply.setSchoolId(orderDetail.getSchoolId());
            subjectsId = orderDetail.getSubjectsId();
        }

        if (stringList.size() > 0) {
            StringBuilder studentBuilder = new StringBuilder();
            studentBuilder.append("班级上课时间存在冲突，保存失败:" + String.join(",", stringList));
            return new Result(Code.ERROR, stringList, studentBuilder.toString());
        }

        applyCount = iOrderApplyService.getApplyCount(subjectsId.toString(), studentId.toString());
        if (applyCount == 0L) {
            EnrollSet enrollSet = iEnrollSetService.findEnrollSetForDate(orderApply.getSchoolId());
            if (enrollSet == null) {
                return new Result(Code.ERROR, "", "招生信息没有设置，请先设置招生信息");
            }
        }
        orderApply.setCreatedId(this.adminId);
        /************************************拉卡拉开始***********************************************/
        LklPay lklPay = new LklPay();
        LklPay pay = new LklPay();
        // 获取当前日期最大时分秒，设置订单有效期时间
        LocalDate today = LocalDate.now();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX).withNano(0);
        if (orderApply.getSignType().equals(3)) {
            // 通过校区id获取商户号
//        Long schoolId = orderApply.getSchoolId();
            String merchantNo = null;
            LklMerchantSet lklMerchantSet = iLklMerchantSetService.getMerchantNo(quarterNow.getYearPart().toString(), quarterNow.getNum().toString(), subjectsId, studentId, orderApply.getSchoolId());
            if (Objects.isNull(lklMerchantSet)){
               return new Result(Code.ERROR, "", "商户号为空,请配置商户号！");
            }
            merchantNo = lklMerchantSet.getMerchantNo();
            orderApply.setPayeeId(lklMerchantSet.getTeacherId());//设置收款人
        //获取学生的账户号
            //支付上线时打开
//        Organization organization = iOrganizationService.getById(orderApply.getSchoolId());
//        LklMerchant lklMerchant = iLklMerchantService.getById(organization.getMerchantId());
//        if (lklMerchant == null) {
//            return new Result(Code.ERROR, "", "拉卡拉商户号为空，请先配置“"+organization.getName()+"”校区使用的商户号");
//        }

            LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
            // 创建一个DateTimeFormatter实例，指定目标格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            // 使用formatter格式化LocalDateTime
            String orderEfficientTime = endOfDay.format(formatter);
            StringBuilder shopName = new StringBuilder();
            shopName.append(iStudentService.getStudentName(orderApply.getStudentId()));
            shopName.append("：");
            shopName.append(CommonUtil.getYearClassNameForId(yearClassId));
            //System.out.println("===================================subjectsId:"+subjectsId);
            shopName.append(CommonUtil.getSubjectsNameForId(Math.toIntExact(subjectsId)));
            // 获取拉卡拉支付链接
            //orderApply.setPrice(new BigDecimal(0.01));//测试数据使用，上线时注释掉
            this.doInit();
            lklPay.setEfficientDateTime(endOfDay);//传过去计算时间使用
            //System.out.println("lklOrderNo:" + lklOrderNo);
            lklPay.setOutOrderNo(lklOrderNo);
            lklPay.setMerchantNo(merchantNo);
            lklPay.setTotalAmount(orderApply.getPrice().multiply(new BigDecimal("100")).longValue());
            lklPay.setOrderEfficientTime(orderEfficientTime);
            lklPay.setShopName(shopName.toString());
            lklPay.setNotifyUrl(notifyUrl);
            pay = iLklPayService.createOrder(lklPay);
            if (!pay.getPaySeccess().equals(1)) {
                return new Result(Code.ERROR, "", "调用拉卡拉创建支付订单失败，请重新提交");
            }
        }
        /************************************拉卡拉结束***********************************************/

        boolean rs = iOrderApplyService.saveTo(orderApply);
        if (rs && orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_SiGN)) {
            try {
                for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                    course = iCourseService.getById(orderDetail.getCourseId());
                    iMqPushService.updateStudentAccount(quarterNow.getYearPart(), quarterNow.getNum(), orderDetail.getStudentId(), orderDetail.getSubjectsId());
                    iMqPushService.updateStudentGradeLast(quarterNow.getYearPart(), course.getQuarterNum(), orderDetail.getStudentId(), course.getSubjectsId(), course.getLessonType());
                    //iStudentGradeService.updateIsPresort(orderDetail.getSchoolId(), orderApply.getStudentId(), quarterNow.getYearPart(), course.getQuarterNum(), course.getSubjectsId(), course.getLessonType());
                    iMqPushService.updateIsPresort(orderDetail.getSchoolId(), orderApply.getStudentId(), quarterNow.getYearPart(), course.getQuarterNum(), course.getSubjectsId(), course.getLessonType());

                }
                Student student = new Student();
                student.setId(orderApply.getStudentId());
                iMqPushService.applyEnrollData(student);
            } catch (Exception e) {

            }
        }
        if (rs && (orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_SiGN) || orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER))) {
            try {
                Integer lessonType = 1;
                Integer yearPart = null;
                Integer quarterNum = null;
                Long schoolId = null;
                for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                    yearPart = orderDetail.getYearPart();
                    quarterNum = orderDetail.getQuarterNum();
                    studentId = orderDetail.getStudentId();
                    subjectsId = orderDetail.getSubjectsId();
                    schoolId = orderDetail.getSchoolId();
                }
                iMqPushService.autoOrderApply(yearPart, quarterNum, schoolId, subjectsId, lessonType, studentId);
            } catch (Exception e) {
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);

        //不为试听学员时调用合并
        iMqPushService.studentMerge(orderApply.getStudentId());


        // 判断是否存在公立在读学期
        if (orderApply.getReadingSchoolId() != null) {
            Quarter quarter = iQuarterService.getNowQuarter();
            Integer gradeSectionId = CommonUtil.getGradeSectionId(yearClassId);

            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("grade_section", gradeSectionId);
            wrapper.eq("student_id", orderApply.getStudentId());
            StudentReadSchool studentReadSchool = iStudentReadSchoolService.getOne(wrapper);

            // 添加到学生校区表（公立）中
            if (studentReadSchool == null) {
                studentReadSchool = new StudentReadSchool();
                studentReadSchool.setStudentId(orderApply.getStudentId());
                studentReadSchool.setYearPart(quarter.getYearPart());
                studentReadSchool.setQuarterNum(quarter.getNum());
                studentReadSchool.setYearClassId(yearClassId);
                studentReadSchool.setGradeSection(gradeSectionId);
                studentReadSchool.setReadingSchoolId(orderApply.getReadingSchoolId());
                iStudentReadSchoolService.save(studentReadSchool);

                Student student = new Student();
                student.setId(orderApply.getStudentId());
                student.setReadingSchoolId(orderApply.getReadingSchoolId());

                iStudentService.updateById(student);
            } else {
                studentReadSchool.setYearPart(quarter.getYearPart());
                studentReadSchool.setQuarterNum(quarter.getNum());
                studentReadSchool.setYearClassId(yearClassId);
                studentReadSchool.setReadingSchoolId(orderApply.getReadingSchoolId());
                iStudentReadSchoolService.updateById(studentReadSchool);

                Student student = new Student();
                student.setId(orderApply.getStudentId());
                student.setReadingSchoolId(orderApply.getReadingSchoolId());

                iStudentService.updateById(student);
            }
        }

        /******推送订单信息给家长**********/
//        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
//        wecharsBindQueryWrapper.eq("student_id", orderApply.getStudentId());
//        List<WecharsBind> wecharsBindList = iWecharsBindService.list(wecharsBindQueryWrapper);
        if (orderApply.getSignType().equals(3)) {
            BigDecimal pushPrice = orderApply.getPrice().setScale(2, RoundingMode.HALF_UP);
            Student student = iStudentService.getById(orderApply.getStudentId());
            iWecharsBindService.pushOrder(student.getName(), course.getName(), String.valueOf(pushPrice), studentId.toString(), lklOrderNo);
        }

        // 返回给前端数据//支付上线时打开
        if (orderApply.getSignType().equals(3)) {
            map.put("counterUrl", pay.getCounterUrl());
            map.put("totalAmount", orderApply.getPrice());
            map.put("shopName", lklPay.getShopName());
            map.put("orderEfficientTime", endOfDay.toString().replace("T", " "));
        }

        return new Result(rs ? Code.OK : Code.ERROR, map, "保存成功");
//        return null;
    }

    /**
     * 添加多条
     *
     * @param orderApplyMoreRs
     * @return
     */
    @RequiresPermissions(value = "manage:apply")
    @PostMapping("/saveMore")
    @RepeatSubmit(expireSeconds = 30)
    public Result saveMore(@RequestBody OrderApplyMoreRs orderApplyMoreRs) throws Exception {
        Quarter quarterNow = iQuarterService.getNowQuarter();

        //生成拉卡拉订单号
        //String lklOrderNo = "KFPT" + CommonUtil.getLklOrderNo();
        Long studentId = 0L;
        Long schoolId = 0L;
        BigDecimal price = new BigDecimal("0");

        StringBuilder shopName = new StringBuilder();

        Integer i = 0;
        for (OrderApply orderApply : orderApplyMoreRs.getOrderApplyList()) {
            studentId = orderApply.getStudentId();
            if (i.equals(0)) {
                shopName.append(iStudentService.getStudentName(studentId));
                shopName.append("：");
            }
            Long orderId = idWorker.nextId();
            orderApply.setId(orderId);
            //orderApply.setLklOrderNo(lklOrderNo);
            //orderApply.setStatus(StatusOrderApplyEnum.TOVOID);//设置为课时未生效
            //orderApply.setSignType(3);

//            Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
//            if (count > 0) {
//                //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
//            }
            if (StringUtils.isBlank(orderApply.getReceiptNo())) {
                Integer receiptNo = CommonUtil.getReceiptNo();
                orderApply.setReceiptNo(receiptNo.toString());
            }
            LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);
            List<String> stringList = new ArrayList<>();
            Long subjectsId = 0L;
            Long applyCount = 0L;
            for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                Course course = iCourseService.getById(orderDetail.getCourseId());
                if (i > 0) {
                    shopName.append("、");
                }
                shopName.append(CommonUtil.getYearClassNameForId(course.getYearClassId().getKey()));
                shopName.append(CommonUtil.getSubjectsNameForId(Math.toIntExact(course.getSubjectsId())));

                //orderDetail.setLklOrderNo(lklOrderNo);
                //orderDetail.setStatus(StatusOrderApplyEnum.TOVOID);//设置为课时未生效
                //orderDetail.setSignType(3);
                //添加当前报读的续班信息
                Integer yearPart = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
                if (orderDetail.getGradeId() != null) {
                    String clashStr = "";
                    List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(yearPart, course.getQuarterNum(), orderDetail.getStudentId(), orderDetail.getGradeId(), nowDateTime.toString());
                    if (repairCourseList.size() > 0) {
                        Student student = iStudentService.getById(orderDetail.getStudentId());
                        for (RepairCourse repairCourse : repairCourseList) {
                            clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                            stringList.add(clashStr);
                        }
                    }
                }
                orderApply.setSchoolId(orderDetail.getSchoolId());
                subjectsId = orderDetail.getSubjectsId();
                schoolId = orderDetail.getSchoolId();
            }

            // 通过校区id获取商户号
            //Organization organization = iOrganizationService.getById(orderApply.getSchoolId());
            //LklMerchant lklMerchant = iLklMerchantService.getById(organization.getMerchantId());
            //if (lklMerchant == null) {
            //    return new Result(Code.ERROR, "", "拉卡拉商户号为空，请先配置“" + organization.getName() + "”校区使用的商户号");
            //}

            if (stringList.size() > 0) {
                StringBuilder studentBuilder = new StringBuilder();
                studentBuilder.append("班级上课时间存在冲突，保存失败:" + String.join(",", stringList));
                return new Result(Code.ERROR, stringList, studentBuilder.toString());
            }

            applyCount = iOrderApplyService.getApplyCount(subjectsId.toString(), studentId.toString());
            if (applyCount == 0L) {
                EnrollSet enrollSet = iEnrollSetService.findEnrollSetForDate(orderApply.getSchoolId());
                if (enrollSet == null) {
                    return new Result(Code.ERROR, "", "招生信息没有设置，请先设置招生信息");
                }
            }
            price = price.add(orderApply.getPrice());
            i++;
        }

        /************************************拉卡拉开始***********************************************/
        // 获取当前日期最大时分秒，设置订单有效期时间
        LocalDate today = LocalDate.now();

        /*
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX).withNano(0);
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
        // 创建一个DateTimeFormatter实例，指定目标格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 使用formatter格式化LocalDateTime
        String orderEfficientTime = endOfDay.format(formatter);

        // 通过校区id获取商户号
        Organization organization = iOrganizationService.getById(schoolId);
        LklMerchant lklMerchant = iLklMerchantService.getById(organization.getMerchantId());

        // 获取拉卡拉支付链接
        this.doInit();
        LklPay lklPay = new LklPay();
        lklPay.setEfficientDateTime(endOfDay);//传过去计算时间使用
        lklPay.setOutOrderNo(lklOrderNo);
        //lklPay.setMerchantNo(lklMerchant.getMerchantNo());
        lklPay.setTotalAmount(price.multiply(new BigDecimal("100")).longValue());
        //lklPay.setTotalAmount(1L);
        lklPay.setOrderEfficientTime(orderEfficientTime);
        lklPay.setShopName(shopName.toString());
        lklPay.setNotifyUrl(notifyUrl);
        LklPay pay = iLklPayService.createOrder(lklPay);
        if (!pay.getPaySeccess().equals(1)) {
            return new Result(Code.ERROR, "", "调用拉卡拉创建支付订单失败，请重新提交");
        }*/
        /************************************拉卡拉结束***********************************************/
        boolean bool = true;
        Integer yearClassId = 0;
        Long readingSchoolId = 0L;

        List<Map<String, Object>> orderApplyList = new ArrayList<>();

        for (OrderApply orderApply : orderApplyMoreRs.getOrderApplyList()) {
            Long orderId = idWorker.nextId();
            orderApply.setId(orderId);
            if (StringUtils.isBlank(orderApply.getReceiptNo())) {
                Integer receiptNo = CommonUtil.getReceiptNo();
                orderApply.setReceiptNo(receiptNo.toString());
            }

            Long subjectsId = 0L;
            yearClassId = orderApply.getYearClassId();
            readingSchoolId = orderApply.getReadingSchoolId();
            orderApply.setCreatedId(this.adminId);
            boolean rs = iOrderApplyService.saveTo(orderApply);
            if (!rs) {
                bool = false;
            }

            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("orderId", orderId);

            if (rs && orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_SiGN)) {
                try {
                    for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                        Course course = iCourseService.getById(orderDetail.getCourseId());
                        hashMap.put("subjectId", orderDetail.getSubjectsId());
                        iMqPushService.updateStudentAccount(quarterNow.getYearPart(), quarterNow.getNum(), orderDetail.getStudentId(), orderDetail.getSubjectsId());
                        iMqPushService.updateStudentGradeLast(quarterNow.getYearPart(), course.getQuarterNum(), orderDetail.getStudentId(), course.getSubjectsId(), course.getLessonType());
                        iMqPushService.updateIsPresort(orderDetail.getSchoolId(), orderApply.getStudentId(), quarterNow.getYearPart(), course.getQuarterNum(), course.getSubjectsId(), course.getLessonType());
                    }
                    Student student = new Student();
                    student.setId(orderApply.getStudentId());
                    iMqPushService.applyEnrollData(student);
                } catch (Exception e) {
                }
            }
            if (rs && (orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_SiGN) || orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER))) {
                try {
                    Integer lessonType = 1;
                    Integer yearPart = null;
                    Integer quarterNum = null;
                    for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                        yearPart = orderDetail.getYearPart();
                        quarterNum = orderDetail.getQuarterNum();
                        subjectsId = orderDetail.getSubjectsId();
                        schoolId = orderDetail.getSchoolId();
                        iMqPushService.autoOrderApply(yearPart, quarterNum, schoolId, subjectsId, lessonType, studentId);
                    }
                } catch (Exception e) {
                }
            }
            orderApplyList.add(hashMap);
        }


        //不为试听学员时调用合并
        iMqPushService.studentMerge(studentId);

        // 判断是否存在公立在读学期
        if (readingSchoolId != null) {
            Quarter quarter = iQuarterService.getNowQuarter();
            Integer gradeSectionId = CommonUtil.getGradeSectionId(yearClassId);

            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("grade_section", gradeSectionId);
            wrapper.eq("student_id", studentId);
            StudentReadSchool studentReadSchool = iStudentReadSchoolService.getOne(wrapper);

            // 添加到学生校区表（公立）中
            if (studentReadSchool == null) {
                studentReadSchool = new StudentReadSchool();
                studentReadSchool.setStudentId(studentId);
                studentReadSchool.setYearPart(quarter.getYearPart());
                studentReadSchool.setQuarterNum(quarter.getNum());
                studentReadSchool.setYearClassId(yearClassId);
                studentReadSchool.setGradeSection(gradeSectionId);
                studentReadSchool.setReadingSchoolId(readingSchoolId);
                iStudentReadSchoolService.save(studentReadSchool);

                Student student = new Student();
                student.setId(studentId);
                student.setReadingSchoolId(readingSchoolId);
                iStudentService.updateById(student);

            } else {
                studentReadSchool.setYearPart(quarter.getYearPart());
                studentReadSchool.setQuarterNum(quarter.getNum());
                studentReadSchool.setYearClassId(yearClassId);
                studentReadSchool.setReadingSchoolId(readingSchoolId);
                iStudentReadSchoolService.updateById(studentReadSchool);

                Student student = new Student();
                student.setId(studentId);
                student.setReadingSchoolId(readingSchoolId);
                iStudentService.updateById(student);
            }
        }

//        boolean rs = iOrderApplyService.saveToMore(orderApplyMoreRs);
        Map<String, Object> map = new HashMap<>();
        map.put("orderApplyList", orderApplyList);
        //map.put("counterUrl", pay.getCounterUrl());
        map.put("totalAmount", price);
        //map.put("shopName", lklPay.getShopName());
        //map.put("orderEfficientTime", endOfDay.toString().replace("T", " "));
        return new Result(bool ? Code.OK : Code.ERROR, map, "保存成功");
    }


    @RequiresPermissions(value = "manage:discount")
    @PostMapping("/addOrderDisPrice")
    @RepeatSubmit(expireSeconds = 5)
    public Result addOrderDisPrice(@RequestBody OrderDetail orderDetail) {
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderDetail.getOrderId());
        orderDetailQueryWrapper.last("limit 1");
        OrderDetail orderDetailOld = iOrderDetailService.getOne(orderDetailQueryWrapper);
        if (orderDetailOld.getResiduePrice().compareTo(orderDetail.getDiscountsPrice()) < 0) {
            return new Result(Code.ERROR, "", "余额不足，操作失败");
        }


        iOrderApplyService.addOrderDisDetaill(orderDetail.getStudentList(), orderDetail.getOrderId(), orderDetail.getOrderDisDetailList(), orderDetail.getDiscountsPrice(), orderDetail.getDiscountsDate(), this.adminId);
        return new Result(Code.OK, "", "添加成功");
    }


    /**
     * 删除优惠
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delDisPrice/{id}")
    public Result delDisPrice(@PathVariable(value = "id") Long id) {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        OrderDisPrice orderDisPrice = iOrderDisPriceService.getById(id);
        if (orderDisPrice == null) {
            return new Result(Code.ERROR, "", "优惠数据不存在，删除失败");
        }

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderDisPrice.getOrderId());
        orderDetailQueryWrapper.last("limit 1");
        OrderDetail orderDetailOld = iOrderDetailService.getOne(orderDetailQueryWrapper);
        if (orderDetailOld.getResidueCourseCount().equals(1)) {
            return new Result(Code.ERROR, "", "没有剩余课时，不能删除");
        }

        if (!orderDetailOld.getYearPart().equals(quarterNow.getYearPart()) && !orderDetailOld.getQuarterNum().equals(quarterNow.getNum())) {
            return new Result(Code.ERROR, "", "删除失败，不能删除非当前学期优惠");
        }

        iOrderDisPriceService.delDisPrice(orderDisPrice, 1);
        return new Result(Code.OK, "", "添加成功");
    }

    /**
     * 是否添加过
     *
     * @param orderApply
     * @return
     */
    @RequiresPermissions(value = "manage:apply")
    @PostMapping("/isAddPass")
    public Result isAddPass(@RequestBody OrderApply orderApply) {
        LocalDate dateNow = LocalDate.now();
        LocalDate dateBefore = dateNow.minusDays(1);

        List<OrderApply> orderApplyList = new ArrayList<>();
        for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
            Course course = iCourseService.getById(orderDetail.getCourseId());
            Integer allCourseCount = orderDetail.getAllCourseCount();
            //添加当前报读的续班信息
            Integer yearPart = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("year_part", yearPart);
            orderDetailQueryWrapper.eq("quarter_num", course.getQuarterNum());
            orderDetailQueryWrapper.eq("lesson_type", course.getLessonType());
            orderDetailQueryWrapper.eq("order_type", 1);
            orderDetailQueryWrapper.eq("student_id", orderApply.getStudentId());
            orderDetailQueryWrapper.ne("status", 2);
            orderDetailQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
            orderDetailQueryWrapper.eq("all_course_count", allCourseCount);
            //orderDetailQueryWrapper.gt("residue_course_count",30);
            //orderDetailQueryWrapper.le("use_course_count", 9);
            orderDetailQueryWrapper.between("handle_date", dateBefore, dateNow);
            List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
            for (OrderDetail orderDetailNew : orderDetailList) {
                //long daysDiff = ChronoUnit.DAYS.between(dateNow, orderDetailNew.getHandleDate());


                OrderApply orderApplyNew = iOrderApplyService.getOneForId(orderDetailNew.getOrderId());
                if (orderApplyNew != null) {
                    orderApplyList.add(orderApplyNew);
                }
            }
        }
        return new Result(Code.OK, orderApplyList, "获取成功");
    }

    /**
     * 多科是否添加过
     *
     * @param orderApplyMoreRs
     * @return
     */
    @RequiresPermissions(value = "manage:apply")
    @PostMapping("/isAddPassMore")
    public Result isAddPassMore(@RequestBody OrderApplyMoreRs orderApplyMoreRs) throws ParseException {
        LocalDate dateNow = LocalDate.now();
        LocalDate dateBefore = dateNow.minusDays(1);
        List<OrderApply> orderApplyList = new ArrayList<>();

        for (OrderApply orderApply : orderApplyMoreRs.getOrderApplyList()) {
            for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                Course course = iCourseService.getById(orderDetail.getCourseId());
                Integer allCourseCount = orderDetail.getAllCourseCount();
                //添加当前报读的续班信息
                Integer yearPart = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份
                QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                orderDetailQueryWrapper.eq("year_part", yearPart);
                orderDetailQueryWrapper.eq("quarter_num", course.getQuarterNum());
                orderDetailQueryWrapper.eq("lesson_type", course.getLessonType());
                orderDetailQueryWrapper.eq("order_type", 1);
                orderDetailQueryWrapper.eq("student_id", orderApply.getStudentId());
                orderDetailQueryWrapper.ne("status", 2);
                orderDetailQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                orderDetailQueryWrapper.eq("all_course_count", allCourseCount);
                orderDetailQueryWrapper.between("handle_date", dateBefore, dateNow);
                List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
                for (OrderDetail orderDetailNew : orderDetailList) {
                    OrderApply orderApplyNew = iOrderApplyService.getOneForId(orderDetailNew.getOrderId());
                    if (orderApplyNew != null) {
                        orderApplyList.add(orderApplyNew);
                    }
                }
            }
        }

        return new Result(Code.OK, orderApplyList, "获取成功");
    }


    /**
     * @return
     * @RequiresPermissions(value = {"elevator:view", "onlineMonitoring:view"}, logical = Logical.OR)
     * Logical.OR是指value 中的权限任选其一
     * Logical.AND是指value 中的权限都要有，默认为and
     * <p>
     * 转课保存
     */
    @RequiresPermissions(value = "manage:convey")
    @PostMapping("/transferSave")
    @RepeatSubmit(expireSeconds = 5)
    public Result transferSave(@RequestBody OrderApply orderApply) throws ParseException {
        Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
        if (count > 0) {
            //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            Integer receiptNo = CommonUtil.getReceiptNo();
            orderApply.setReceiptNo(receiptNo.toString());
        }
        iOrderApplyService.saveTo(orderApply);
        return new Result(Code.OK);
    }

    /**
     * 修改经办日期
     *
     * @param orderApply
     * @return
     */
    @RequiresPermissions(value = "manage:date")
    @PutMapping("/updateHandelDate")
    public Result updateHandelDate(@RequestBody OrderApply orderApply) {
        iOrderApplyService.updateDate(orderApply);
        return new Result(Code.OK);
    }


    /**
     * 退费
     *
     * @param orderApply
     * @return
     */
    @RequiresPermissions(value = "manage:back")
    @PostMapping("/refundSave")
    @RepeatSubmit(expireSeconds = 5)
    public Result refundSave(@RequestBody OrderApply orderApply) throws ParseException {
        Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
        if (count > 0) {
            //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            Integer receiptNo = CommonUtil.getReceiptNo();
            orderApply.setReceiptNo(receiptNo.toString());
        }

        List<OrderTransferDetail> orderTransferDetailList = orderApply.getOrderTransferDetailList();
        Integer yearPart = 0;
        Integer quarterNum = 0;
        Long studentId = orderApply.getStudentId();
        Long subjectsId = 0L;
        Integer lessonType = 1;
        Long schoolId = 0L;

        OrderDetail orderDetail;
        for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
            orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
            yearPart = orderDetail.getYearPart();
            quarterNum = orderDetail.getQuarterNum();
            subjectsId = orderDetail.getSubjectsId();
            schoolId = orderDetail.getSchoolId();
        }

        /**
         * 还有请假未被的
         */
        Integer lackCount = iRecordCourseService.getLackCount(yearPart, quarterNum, schoolId, studentId, subjectsId, lessonType);
        if (lackCount > 0) {
            Student student = iStudentService.getById(studentId);
            return new Result(Code.ERROR, "", "”" + student.getName() + "“学生还有请假未补的记上课，请先处理再退费");
        }


        boolean rs = iOrderApplyService.saveTo(orderApply);
        if (rs) {
            Integer orderType = orderApply.getOrderType().getKey();
            //添加智能课或者刷题班
//            try{
//                Integer lessonType = 1;//精品课
//                if(orderType == Code.ORDER_TYPE_SiGN || orderType == Code.ORDER_TYPE_REFUND){
//                    //报名，退费
//                    iOrderDetailService.addOrderApply(yearPart,quarterNum,orderApply.getSchoolId(),subjectsId,lessonType,orderApply.getStudentId());
//                }else if (orderType == Code.ORDER_TYPE_TRANSFER){
//                    //转课
//                    if (outSubjectsId != inSubjectsId){
//                        //iOrderDetailService.addOrderApply(yearPart,quarterNum,orderTransfer.getOutSchoolId(),outSubjectsId,lessonType,orderApply.getStudentId());
//                        iOrderDetailService.addOrderApply(yearPart,quarterNum,orderTransfer.getInSchoolId(),inSubjectsId,lessonType,orderApply.getStudentId());
//
//                    }
//                }
//            }catch (Exception e){
//
//            }

            // 同步到英语修改学员在读状态
            if (subjectsId == 1) {
                StudentClassType studentClassType = new StudentClassType();
                studentClassType.setStudentId(orderApply.getStudentId());
                studentClassType.setReadingStatus(3);
                studentClassType.setYearPart(yearPart);
                studentClassType.setQuarterNum(quarterNum);
                //rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_SYNC_EXCLUDE_CLASS_TYPE, null, studentClassType);
            }

        }
        return new Result(Code.OK);
    }

    /**
     * 补费
     *
     * @param orderApply
     * @return
     */
    @RequiresPermissions(value = "manage:repair")
    @PostMapping("/suppSave")
    @RepeatSubmit(expireSeconds = 5)
    public Result suppSave(@RequestBody OrderApply orderApply) throws ParseException {
        Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
        if (count > 0) {
            //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            Integer receiptNo = CommonUtil.getReceiptNo();
            orderApply.setReceiptNo(receiptNo.toString());
        }
        iOrderApplyService.saveTo(orderApply);
        return new Result(Code.OK);
    }

    /**
     * 转校
     *
     * @param orderApply
     * @return
     */
    @RequiresPermissions(value = "manage:transfer")
    @PostMapping("/transferSchoolSave")
    @RepeatSubmit(expireSeconds = 5)
    public Result transferSchoolSave(@RequestBody OrderApply orderApply) throws ParseException {
        Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
        if (count > 0) {
            //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            Integer receiptNo = CommonUtil.getReceiptNo();
            orderApply.setReceiptNo(receiptNo.toString());
        }


        List<OrderTransferDetail> orderTransferDetailList = orderApply.getOrderTransferDetailList();
        Integer yearPart = 0;
        Integer quarterNum = 0;
        Long studentId = orderApply.getStudentId();
        Long subjectsId = 0L;
        Integer lessonType = 1;
        Long schoolId = 0L;

        OrderDetail orderDetail;
        for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
            orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
            yearPart = orderDetail.getYearPart();
            quarterNum = orderDetail.getQuarterNum();
            subjectsId = orderDetail.getSubjectsId();
            schoolId = orderDetail.getSchoolId();
        }

        /**
         * 还有请假未被的
         */
        Integer lackCount = iRecordCourseService.getLackCount(yearPart, quarterNum, schoolId, studentId, subjectsId, lessonType);
        if (lackCount > 0) {
            Student student = iStudentService.getById(studentId);
            return new Result(Code.ERROR, "", "”" + student.getName() + "“学生还有请假未补的记上课，请先处理再转校");
        }

        Integer notAffirmCount = iOrderApplyService.getNotAffirmCount(yearPart, quarterNum, schoolId, studentId, subjectsId.toString());

        if (notAffirmCount > 0) {
            Student student = iStudentService.getById(studentId);
            return new Result(Code.ERROR, "", "”" + student.getName() + "“学生还有报名订单未确认，请先确认再转校");
        }

        iOrderApplyService.transferSchoolSave(orderApply);
        iOrderDetailService.updateStudentResidueCourseCount(yearPart, quarterNum, orderApply.getStudentId());
        return new Result(Code.OK);
    }

    /**
     * 批量转校
     *
     * @param orderApply
     * @return
     */
    @PostMapping("/batchTransferSchoolSave")
    @RepeatSubmit(expireSeconds = 5)
    public Result batchTransferSchoolSave(@RequestBody OrderApply orderApply) throws ParseException {
        orderApply.setHandlePersonId(this.adminId);
        if (this.staffInfo != null) {
            orderApply.setHandlePersonName(this.staffInfo.getName());
        } else if (this.isSuper.equals(1)) {
            orderApply.setHandlePersonName("超级管理员");
        }

        Result rs = iOrderApplyService.batchTransferSchoolSave(orderApply);
        return rs;
    }


    /**
     * 转科目
     *
     * @param orderApply
     * @return
     */
    @RequiresPermissions(value = "manage:transfer")
    @PostMapping("/transferSubjectSave")
    @RepeatSubmit(expireSeconds = 5)
    public Result transferSubjectSave(@RequestBody OrderApply orderApply) throws ParseException {
        Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
        if (count > 0) {
            //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            Integer receiptNo = CommonUtil.getReceiptNo();
            orderApply.setReceiptNo(receiptNo.toString());
        }


        List<OrderTransferDetail> orderTransferDetailList = orderApply.getOrderTransferDetailList();
        Integer yearPart = 0;
        Integer quarterNum = 0;
        Long studentId = orderApply.getStudentId();
        Long subjectsId = 0L;
        Integer lessonType = 1;
        Long schoolId = 0L;

        OrderDetail orderDetail;
        for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
            orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
            yearPart = orderDetail.getYearPart();
            quarterNum = orderDetail.getQuarterNum();
            subjectsId = orderDetail.getSubjectsId();
            schoolId = orderDetail.getSchoolId();
        }

        /**
         * 还有请假未补的
         */
        Integer lackCount = iRecordCourseService.getLackCount(yearPart, quarterNum, schoolId, studentId, subjectsId, lessonType);
        if (lackCount > 0) {
            Student student = iStudentService.getById(studentId);
            return new Result(Code.ERROR, "", "”" + student.getName() + "“学生还有请假未补的记上课，请先处理再转科目");
        }

        Integer notAffirmCount = iOrderApplyService.getNotAffirmCount(yearPart, quarterNum, schoolId, studentId, subjectsId.toString());

        if (notAffirmCount > 0) {
            Student student = iStudentService.getById(studentId);
            return new Result(Code.ERROR, "", "”" + student.getName() + "“学生还有报名订单未确认，请先确认再转科目");
        }

        iOrderApplyService.transferSubjectSave(orderApply);
        iOrderDetailService.updateStudentResidueCourseCount(yearPart, quarterNum, orderApply.getStudentId());
        return new Result(Code.OK);
    }

    /**
     * 转名额
     *
     * @param orderApply
     * @return
     */
    @RequiresPermissions(value = "manage:transfer")
    @PostMapping("/transferStudentSave")
    @RepeatSubmit(expireSeconds = 5)
    public Result transferStudentSave(@RequestBody OrderApply orderApply) throws ParseException {
        Long count = iOrderApplyService.count(new QueryWrapper<OrderApply>().eq("receipt_no", orderApply.getReceiptNo()).ne("status", 2));
        if (count > 0) {
            //return new Result(Code.ERROR,"","收据编码已存在，不能添加重复的收据编码");
        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            Integer receiptNo = CommonUtil.getReceiptNo();
            orderApply.setReceiptNo(receiptNo.toString());
        }


        List<OrderTransferDetail> orderTransferDetailList = orderApply.getOrderTransferDetailList();
        Integer yearPart = 0;
        Integer quarterNum = 0;
        Long studentId = orderApply.getStudentId();
        Long subjectsId = 0L;
        Integer lessonType = 1;
        Long schoolId = 0L;

        OrderDetail orderDetail;
        for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
            orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());
            yearPart = orderDetail.getYearPart();
            quarterNum = orderDetail.getQuarterNum();
            subjectsId = orderDetail.getSubjectsId();
            schoolId = orderDetail.getSchoolId();
        }

        /**
         * 还有请假未补的
         */
        Integer lackCount = iRecordCourseService.getLackCount(yearPart, quarterNum, schoolId, studentId, subjectsId, lessonType);
        if (lackCount > 0) {
            Student student = iStudentService.getById(studentId);
            return new Result(Code.ERROR, "", "”" + student.getName() + "“学生还有请假未补的记上课，请先处理再转名额");
        }

        Integer notAffirmCount = iOrderApplyService.getNotAffirmCount(yearPart, quarterNum, schoolId, studentId, subjectsId.toString());

        if (notAffirmCount > 0) {
            Student student = iStudentService.getById(studentId);
            return new Result(Code.ERROR, "", "”" + student.getName() + "“学生还有报名订单未确认，请先确认再转名额");
        }

        iOrderApplyService.transferStudentSave(orderApply);
        return new Result(Code.OK);
    }


    @GetMapping("/batchTransferSchoolSaveTemp")
    public Result batchTransferSchoolSaveTemp() throws ParseException {
        OrderApply orderApply = new OrderApply();
        orderApply.setHandlePersonId(this.adminId);

        orderApply.setOutSchoolId(1600459215889801217L);
        orderApply.setSchoolId(1812055654697795585L);

        List<Long> studentList = new ArrayList<>();
        //List<Long> studentList = orderDetailMapper.getChangeSchool();
        orderApply.setStudentList(studentList);
        List<Long> subjectsIdList = new ArrayList<>();
        subjectsIdList.add(1L);
        subjectsIdList.add(2L);
        subjectsIdList.add(3L);
        subjectsIdList.add(4L);

        orderApply.setSubjectsList(subjectsIdList);

        orderApply.setHandlePersonId(this.adminId);
        if (this.staffInfo != null) {
            orderApply.setHandlePersonName(this.staffInfo.getName());
        } else if (this.isSuper.equals(1)) {
            orderApply.setHandlePersonName("超级管理员");
        }


        Result rs = iOrderApplyService.batchTransferSchoolSave(orderApply);
        return rs;
    }


    @GetMapping("/checkCourse")
    public Result checkCourse(@RequestParam Map<String, String> reMap,
                              @RequestParam(value = "schoolId", defaultValue = "") Long schoolId,
                              @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList,
                              @RequestParam(value = "subjectsId", defaultValue = "") String[] subjectsIdArr,
                              @RequestParam(value = "quarterNumList", defaultValue = "") String[] quarterNumList,
                              @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));
        IPage<Map<String, Object>> iPage = new Page<>(pageNum, pageSize);

        Quarter quarter = iQuarterService.getNowQuarter();

        String keyword = reMap.get("keyword");

        QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.status", 1);
        queryWrapper.eq("a.deleted", 0);
        //System.out.print("schoolId："+schoolId);
        //System.out.println();
        if (schoolId != null) {
            queryWrapper.and(i -> i.eq("a.opening_school_type", 1).or().inSql("a.id", "select for_id from appoint_school where type=1 and school_id =" + schoolId));
        } else {
            //System.out.print("baseSchoolIdStr:"+baseSchoolIdStr);
            queryWrapper.and(i -> i.eq("a.opening_school_type", 1).or().inSql("a.id", "select for_id from appoint_school where type=1 and school_id in(" + this.baseSchoolIdStr + ")"));
        }


        if (yearClassIdList.length > 0) {
            queryWrapper.in("a.year_class_id", yearClassIdList);
        }
        if (subjectsIdArr.length > 0) {
            queryWrapper.in("a.subjects_id", subjectsIdArr);
        }
        if (quarterNumList.length > 0) {
            queryWrapper.in("a.quarter_num", quarterNumList);
        } else {
            queryWrapper.eq("a.quarter_num", quarter.getNum());
        }

        if (StringUtils.isNotBlank(keyword)) {
            //queryWrapper.and(i->i.like("name",keyword).or(j->j.like("linkman_phone",name)));
            queryWrapper.like("a.name", keyword);
        }
        //queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        iCourseService.checkCourse(iPage, queryWrapper, schoolId);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/checkCourseOne/{courseId}/{schoolId}")
    public Result checkCourseOne(@RequestParam(value = "courseId", defaultValue = "") String courseId,
                                 @RequestParam(value = "schoolId", defaultValue = "") Long schoolId) {

        IPage<Course> iPage = new Page<>(1, 10);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("a.id", courseId);
        iCourseService.checkCourse(iPage, queryWrapper, schoolId);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    @GetMapping("/checkGrade")
    public Result checkGrade(@RequestParam Map reMap,
                             @RequestParam(value = "studentId", required = false) Long studentId,
                             @RequestParam(value = "subjectsId", defaultValue = "") String[] subjectsId,
                             @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList,
                             @RequestParam(value = "quarterNumList", defaultValue = "") String[] quarterNumList) {

        String schoolId = (String) reMap.get("schoolId");
        String keyword = reMap.get("keyword").toString();

        Quarter quarterNow = iQuarterService.getNowQuarter();


        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Grade> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.deleted", 0);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "a.school_id", schoolId);

        Long subjectsOne = 0L;
        if (subjectsId.length > 0) {
            queryWrapper.in("b.subjects_id", subjectsId);
            subjectsOne = Long.parseLong(subjectsId[0]);
        }

        if (StringUtils.isNotBlank(keyword)) {
            //queryWrapper.and(i->i.like("name",keyword).or(j->j.like("linkman_phone",name)));
            queryWrapper.like("a.name", keyword);
        }

        Integer yearClassIdOne = 0;
        if (yearClassIdList.length > 0) {
            queryWrapper.in("b.year_class_id", yearClassIdList);
            yearClassIdOne = Integer.parseInt(yearClassIdList[0]);
        }

        if (quarterNumList.length > 0) {
            queryWrapper.in("b.quarter_num", quarterNumList);
        } else {
            queryWrapper.in("b.quarter_num", quarterNow.getNum());
        }
        queryWrapper.eq("a.status", 1);
        queryWrapper.in("a.year_part", quarterNow.getYearPart());
        if (studentId != null) {
            Company company = iCompanyService.getById(CommonConstant.companyId);
            if (company != null) {
                if (company.getStuIsHierarchy().equals(1)) {
                    Long count = iOrderApplyService.getApplyCountForIsNew(subjectsOne.toString(), studentId.toString());
                    //为0新生
                    if (count.equals(0L)) {
                        GradePositionRequest gradePositionRequest = iStudentClassTypeService.getAutoDivideClassTypeOrScore(quarterNow.getYearPart(), quarterNow.getNum(), subjectsOne, studentId, yearClassIdOne);
                        if (gradePositionRequest.getIsHasData().equals(1)) {
                            List<Grade> positionGradeList = iGradeService.getPositionGradeList(quarterNow.getYearPart(), quarterNow.getNum(), Long.parseLong(schoolId), subjectsOne, yearClassIdOne, 1, gradePositionRequest.getType(), gradePositionRequest.getScore(), gradePositionRequest.getClassTypeId());
                            if (positionGradeList.size() > 0) {
                                Grade grade = positionGradeList.get(0);
                                queryWrapper.in("a.id", grade.getId());
                            } else {
                                queryWrapper.in("a.id", 0);//显示没有
                            }
                        }
                    }
                }
            }
        }
        queryWrapper.orderByDesc("a.id");
        iGradeService.checkGrade(iPage, queryWrapper, Long.parseLong(schoolId));
        //return new Result(Code.OK,list);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 获取报读课程
     *
     * @param
     * @return
     */
    @GetMapping("/getLessonByStuInfoId/{studentId}")
    public Result getLessonByStuInfoId(@PathVariable(value = "studentId") Long studentId,
                                       @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {

        //where b.`status` <> 2  and a.residue_course_count > 0 and a.student_id = #{studentId} and a.deleted=0  group by course_id order by a.id desc
        QueryWrapper<OrderApply> orderApplyQueryWrapper = new QueryWrapper<>();
        orderApplyQueryWrapper.ne("b.status", 2);
        orderApplyQueryWrapper.gt("a.residue_course_count", 0);
        orderApplyQueryWrapper.eq("b.student_id", studentId);
        orderApplyQueryWrapper.eq("a.deleted", 0);
        orderApplyQueryWrapper.eq("a.lesson_type", lessonType);
        orderApplyQueryWrapper.groupBy("course_id");
        orderApplyQueryWrapper.orderByDesc("a.id");

        if (this.baseSchoolIdList.size() > 0) {
            orderApplyQueryWrapper.in("a.school_id", this.baseSchoolIdList);
        } else {
            orderApplyQueryWrapper.eq("a.school_id", 0);
        }

        List<OrderDetail> orderDetailList = iOrderDetailService.GetLessonByStuInfoId(orderApplyQueryWrapper);
        return new Result(Code.OK, orderDetailList);
    }

    @GetMapping("/getSubjectsByStuInfoId/{studentId}")
    public Result getSubjectsByStuInfoId(@PathVariable(value = "studentId") Long studentId) {

        //where b.`status` <> 2  and a.residue_course_count > 0 and a.student_id = #{studentId} and a.deleted=0  group by course_id order by a.id desc
        QueryWrapper<OrderApply> orderApplyQueryWrapper = new QueryWrapper<>();
        orderApplyQueryWrapper.ne("a.status", 2);
        orderApplyQueryWrapper.gt("a.residue_course_count", 0);
        orderApplyQueryWrapper.eq("a.student_id", studentId);
        orderApplyQueryWrapper.eq("a.deleted", 0);
        orderApplyQueryWrapper.eq("a.lesson_type", 1);
        orderApplyQueryWrapper.groupBy("a.subjects_id", "a.school_id");
        orderApplyQueryWrapper.orderByDesc("a.id");

        if (this.baseSchoolIdList.size() > 0) {
            orderApplyQueryWrapper.in("a.school_id", this.baseSchoolIdList);
        } else {
            orderApplyQueryWrapper.eq("a.school_id", 0);
        }

        List<Subjects> subjectsList = iOrderDetailService.GetSubjectsByStuInfoId(orderApplyQueryWrapper);
        return new Result(Code.OK, subjectsList);
    }


    /**
     * 获取报读订单信息(办理中心，选择课程获取报读信息)
     *
     * @return
     */
    @GetMapping("/getStuLeftFee/{studentId}/{courseId}/{schoolId}")
    public Result getStuLeftFee(@PathVariable(value = "studentId") Long studentId, @PathVariable(value = "courseId") Long courseId, @PathVariable(value = "schoolId") Long schoolId) {
        List<OrderDetail> mapList = iOrderDetailService.getLessonByCourseId(courseId, studentId, schoolId);
        return new Result(Code.OK, mapList);
    }

    /**
     * 通过科目获取
     * 获取报读订单信息(办理中心，选择课程获取报读信息)
     *
     * @return
     */
    @GetMapping("/getStuLeftFeeForSubjects/{studentId}/{subjectsId}/{schoolId}")
    public Result getStuLeftFeeForSubjects(@PathVariable(value = "studentId") Long studentId,
                                           @PathVariable(value = "subjectsId") Long subjectsId,
                                           @PathVariable(value = "schoolId") Long schoolId,
                                           @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        List<OrderDetail> mapList = iOrderDetailService.getLessonForSubjects(subjectsId, studentId, schoolId, Integer.parseInt(lessonType));
        return new Result(Code.OK, mapList);
    }


    @GetMapping("orderDetailCourse")
    public Result orderDetailCourse(@RequestParam Map<String, Object> map) {
        QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();
        String courseId = (String) map.get("courseId");
        String studentId = (String) map.get("studentId");

        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.eq(StringUtils.isNotBlank(studentId), "student_id", studentId);

        List<OrderDetail> mapList = iOrderDetailService.orderDetail(queryWrapper);
        return new Result(Code.OK, mapList);
    }

    /**
     * 获取欠费列表
     *
     * @param map
     * @return
     */
    @GetMapping("orderArrears")
    public Result orderArrears(@RequestParam Map<String, Object> map) {
        QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();
        String studentId = (String) map.get("studentId");

        if (StringUtils.isBlank(studentId)) {
            studentId = "0";
        }
        queryWrapper.eq("student_id", studentId);
        //queryWrapper.gt("own_price",0);
        queryWrapper.eq("is_own", 1);

        if (this.baseSchoolIdList.size() > 0) {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        } else {
            queryWrapper.eq("school_id", 0);
        }

        List<Map<String, Object>> mapList = iOrderApplyService.orderArrears(queryWrapper);
        return new Result(Code.OK, mapList);
    }


    /**
     * 校长确认到帐
     *
     * @return
     */
    @RequiresPermissions(value = "manage:confirm")
    @PutMapping("confirmArrive")
    public Result confirmArrive(@RequestBody OrderApply orderApply) {

        Long id = orderApply.getId();
        if (id == null) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        iOrderApplyService.confirmArrive(id, this.adminId, this.isSuper);
        return new Result(Code.OK, "", "操作成功");
    }

    /**
     * 批量确认到款
     *
     * @return
     */
    @RequiresPermissions(value = "manage:confirm")
    @PutMapping("/batchConfirmArrive")
    @Transactional(rollbackFor = Exception.class)
    public Result batchConfirmArrive(@RequestBody Map reMap) {
        List<String> ids = (List<String>) reMap.get("ids");
        if (ids == null || ids.isEmpty()) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        try {
            for (String id : ids) {
                iOrderApplyService.confirmArrive(Long.valueOf(id), this.adminId, this.isSuper);
            }
            return new Result(Code.OK, "", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.ERROR, "", "操作失败");
        }
    }


    /**
     * 财务确认到帐
     *
     * @return
     */
    @PutMapping("financeConfirm")
    public Result financeConfirm(@RequestBody OrderApply orderApply) {

        Long id = orderApply.getId();
        if (id == null) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        iOrderApplyService.financeConfirm(id, this.adminId, this.isSuper);
        return new Result(Code.OK, "", "操作成功");
    }

    /**
     * 取消确认
     *
     * @param orderApply
     * @return
     */
    @PutMapping("moneyAffirm")
    public Result moneyAffirm(@RequestBody OrderApply orderApply) {

        Long id = orderApply.getId();
        if (id == null) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        iOrderApplyService.financeConfirm(id, this.adminId, this.isSuper);
        return new Result(Code.OK, "", "操作成功");
    }

    /**
     * 取消确认
     *
     * @param orderApply
     * @return
     */
    @PutMapping("cancelConfirm")
    public Result cancelConfirm(@RequestBody OrderApply orderApply) {
        Long id = orderApply.getId();
        if (id == null) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        iOrderApplyService.cancelConfirm(id, this.adminId, this.isSuper);
        return new Result(Code.OK, "", "操作成功");
    }

    /**
     * 修改订单号
     *
     * @param orderApply
     * @return
     */
    @PutMapping("/updateReceiptNo")
    public Result updateReceiptNo(@RequestBody OrderApply orderApply) {
        Long id = orderApply.getId();
        if (id == null) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        if (StringUtils.isBlank(orderApply.getReceiptNo())) {
            return new Result(Code.ERROR, "", "订单号不能为空");
        }

        OrderApply orderApplyInfo = iOrderApplyService.getById(id);
        orderApplyInfo.setReceiptNo(orderApply.getReceiptNo());
        iOrderApplyService.updateById(orderApplyInfo);
        return new Result(Code.OK, "", "操作成功");
    }


    /**
     * 订单作废
     *
     * @return
     */
    @RequiresPermissions(value = "manage:del")
    @PutMapping("invalidate")
    public Result invalidate(@RequestBody OrderApply orderApply) throws SDKException {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        String id = orderApply.getId().toString();
        if (id.isEmpty()) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        OrderApply orderApplyNew = iOrderApplyService.getById(orderApply.getId());


        if (quarterNow.getYearPart().equals(orderApplyNew.getYearPart()) && quarterNow.getNum().equals(orderApplyNew.getQuarterNum())) {
        } else {
            return new Result(Code.ERROR, "", "只能作废当前学期订单");
        }
        if (orderApplyNew.getStatus().equals(StatusOrderApplyEnum.TOVOID)) {
            return new Result(Code.ERROR, "", "当前订单已作废，不要重复操作");
        }

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderApply.getId());
        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
        List<String> stringList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            if (orderDetail.getUseCourseCount() > 0) {
                stringList.add("该订单已使用课时，不能作废");
            }
            if (orderDetail.getResidueCourseCount().equals(0)) {
                stringList.add("该订单没有剩余课时，不能作废");
            }
            if (orderDetail.getRollOutHouse() > 0 || orderDetail.getTurnOutHouse() > 0 || orderDetail.getOutHouse() > 0) {
                stringList.add("该订单，不能作废");
            }
        }
        if (stringList.size() > 0) {
            return new Result(Code.ERROR, "", String.join(",", stringList));
        }
        if (orderApplyNew != null && orderApplyNew.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER) && orderApplyNew.getVersion().equals(1)) {
            return new Result(Code.ERROR, "", "课程顺延订单不能作废");
        }

        if (orderApplyNew != null && (orderApplyNew.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_REFUND) || orderApplyNew.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL) || orderApplyNew.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_TRANSFER_REFUND_SCHOOL))) {
            if (this.adminId != 1568138350324350975L) {
                return new Result(Code.ERROR, "", "该订单类型，超级管理员才能作废");
            }
        }

        /*QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.inSql("order_detail_id", "select id from order_detail where order_id = " + orderApplyNew.getId());
        studentGradeQueryWrapper.gt("use_course_count", 0);

        Long count = iStudentGradeService.count(studentGradeQueryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "", "该订单分班信息已使用课时，不能作废");
        }*/




        /*if (!orderApplyNew.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_SiGN) && !orderApplyNew.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_DIS)) {
            //return new Result(Code.ERROR, "", "只有报名和优惠的订单能作废");
        }*/

        if (orderApplyNew.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_DIS)) {
            iOrderApplyService.invalidateDis(orderApply.getId(), adminId, this.isSuper);
        } else {
            iOrderApplyService.invalidate(Long.parseLong(id), this.adminId, this.isSuper);
            try {
                for (OrderDetail orderDetail : orderApply.getOrderDetailList()) {
                    Course course = iCourseService.getById(orderDetail.getCourseId());
                    iMqPushService.updateIsPresort(orderDetail.getSchoolId(), orderApply.getStudentId(), orderDetail.getYearPart(), course.getQuarterNum(), course.getSubjectsId(), course.getLessonType());
                }
            } catch (Exception e) {
            }
        }
        return new Result(Code.OK);
    }

    @GetMapping("getRenewForPay")
    public Result getRenewForPay(@RequestParam Map<String, Object> map) throws ParseException {

        Long schoolId = Long.parseLong(map.get("schoolId").toString());
        Long studentId = Long.parseLong(map.get("studentId").toString());
        Long subjectsId = Long.parseLong(map.get("subjectsId").toString());
        Integer quarterNum = Integer.parseInt(map.get("quarterNum").toString());
        //Thread.sleep(1000);
        //续班信息
        RenewClass renewClass = iQuarterService.getRenewForPay(schoolId, studentId, subjectsId, quarterNum);
        return new Result(Code.OK, renewClass);
    }


    /**
     * 修改优惠
     *
     * @param orderDetail
     * @return
     */
    @RequiresPermissions(value = "manage:discount")
    @PostMapping("/addDiscount")
    public Result addDiscount(@RequestBody OrderDetail orderDetail) {
        //System.out.println("orderId:"+orderDetail.getOrderId());
        //System.out.println();
        //System.out.println("discountsPrice:"+orderDetail.getDiscountsPrice());
        OrderApply orderApply = iOrderApplyService.getById(orderDetail.getOrderId());
        if (!orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_SiGN)) {
            return new Result(Code.ERROR, "", "只有报名的才能添加优惠");
        }

        iOrderApplyService.addDiscount(orderDetail);

        return new Result(Code.OK, "", "添加优惠成功");
    }


    /**
     * @return
     */
    @RequiresPermissions(value = "manage:class_time")
    @PostMapping("/orderHouseChange")
    public Result orderHouseChange(@RequestBody OrderDetail orderDetail) {
        boolean rs = iOrderApplyService.orderHouseChange(orderDetail.getOrderId(), orderDetail.getDiffCount());
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }


    /**
     * 单条数据
     */
    @GetMapping("getOne")
    public Result findGetOne(@RequestParam Map<String, String> reMap) {
        String id = "0";
        if (reMap.get("id") != null) {
            id = reMap.get("id");
        }
        try {
            OrderApply orderApply = iOrderApplyService.getById(Long.valueOf(id));
            BigDecimal discountPrice = orderDetailMapper.getOrderDiscounts(orderApply.getId());
            orderApply.setDiscountsPrice(discountPrice);
            Student student = studentService.getById(orderApply.getStudentId());
            orderApply.setStudentName(student.getName());
            orderApply.setLinkman(student.getLinkman());
            orderApply.setLinkmanPhone(student.getLinkmanPhone());
            return new Result(Code.OK, orderApply);
        } catch (NumberFormatException e) {
            return new Result(Code.ERROR, "", "暂无数据!");
        }
    }

    @PostMapping("/orderPrint")
    public Result orderPrint(@RequestBody Map<String, String> map) {
        Long orderId = Long.parseLong(map.get("orderId").toString());
        OrderApply orderApply = iOrderApplyService.getById(orderId);
        if (orderApply == null) {
            return new Result(Code.ERROR, "", "订单不存在!");
        }
        UpdateWrapper<OrderApply> orderApplyUpdateWrapper = new UpdateWrapper<>();
        orderApplyUpdateWrapper.eq("id", orderId);
        orderApplyUpdateWrapper.set("is_print", 1);

        iOrderApplyService.update(orderApplyUpdateWrapper);
        OrderApplyAffirm orderApplyAffirm = new OrderApplyAffirm();
        orderApplyAffirm.setOrderId(orderId);
        orderApplyAffirm.setType(3);//1收入确认，2优惠确认，3小票打印
        orderApplyAffirm.setAffirmType(0);//1校长确认，2财务确认，3会计确认
        orderApplyAffirm.setAffirmDate(LocalDate.now());
        orderApplyAffirm.setRemark("小票打印");
        iOrderApplyAffirmService.save(orderApplyAffirm);
        return new Result(Code.OK, "", "添加打印记录成功");
    }

    @PostMapping("/orderPrintMore")
    public Result orderPrintMore(@RequestBody Map reMap) {
        List<String> orderIdList = (List<String>) reMap.get("orderIdList");
        for (String orderId : orderIdList) {
            OrderApply orderApply = iOrderApplyService.getById(orderId);
            if (orderApply == null) {
                return new Result(Code.ERROR, "", "订单不存在!");
            }
            UpdateWrapper<OrderApply> orderApplyUpdateWrapper = new UpdateWrapper<>();
            orderApplyUpdateWrapper.eq("id", orderId);
            orderApplyUpdateWrapper.set("is_print", 1);

            iOrderApplyService.update(orderApplyUpdateWrapper);
            OrderApplyAffirm orderApplyAffirm = new OrderApplyAffirm();
            orderApplyAffirm.setOrderId(Long.valueOf(orderId));
            orderApplyAffirm.setType(3);//1收入确认，2优惠确认，3小票打印
            orderApplyAffirm.setAffirmType(0);//1校长确认，2财务确认，3会计确认
            orderApplyAffirm.setAffirmDate(LocalDate.now());
            orderApplyAffirm.setRemark("小票打印");
            iOrderApplyAffirmService.save(orderApplyAffirm);
        }
        return new Result(Code.OK, "", "添加打印记录成功");
    }

    /**
     * 优惠确认
     *
     * @param orderApplyAffirmParam
     * @return
     */
    @PostMapping("/orderAffirmForType")
    public Result orderAffirmForType(@RequestBody OrderApplyAffirm orderApplyAffirmParam) {
        Long orderId = orderApplyAffirmParam.getOrderId();

        Long disId = orderApplyAffirmParam.getId();

        Integer affirmType = 2;//1收入确认，2优惠确认，3小票打印
        Integer type = 2;//1校长确认，2财务确认，3会计确认
        if (orderApplyAffirmParam.getAffirmType() != null) {
            affirmType = orderApplyAffirmParam.getType();
        }
        OrderApply orderApply = iOrderApplyService.getById(orderId);
        if (orderApply == null) {
            return new Result(Code.ERROR, "", "订单不存在!");
        }
        /*UpdateWrapper<OrderApply> orderApplyUpdateWrapper = new UpdateWrapper<>();
        orderApplyUpdateWrapper.eq("id", orderId);
        orderApplyUpdateWrapper.set("arrive_affirm", 2);
        orderApplyUpdateWrapper.set("finance_date", LocalDateTime.now().withNano(0));//确认时间
        iOrderApplyService.update(orderApplyUpdateWrapper);

        UpdateWrapper<OrderDetail> orderDetailUpdateWrapper = new UpdateWrapper<>();
        orderDetailUpdateWrapper.eq("order_id", orderId);
        orderDetailUpdateWrapper.set("arrive_affirm", 2);
        iOrderDetailService.update(orderDetailUpdateWrapper);


        OrderApplyAffirm orderApplyAffirm = new OrderApplyAffirm();
        orderApplyAffirm.setOrderId(orderId);
        orderApplyAffirm.setType(affirmType);//1收入确认，2优惠确认，3小票打印
        orderApplyAffirm.setAffirmType(type);//1校长确认，2财务确认，3会计确认
        orderApplyAffirm.setAffirmDate(LocalDate.now());
        orderApplyAffirm.setRemark("优惠确认");
        iOrderApplyAffirmService.save(orderApplyAffirm);*/
        //iOrderApplyAffirmService.addAffirm(orderId,2,1,"优惠确认",this.adminId);
        iOrderApplyAffirmService.addDisAffirm(disId, orderId, 2, 1, "优惠确认", this.adminId);

        return new Result(Code.OK, "", "添加打印记录成功");
    }


    @PostMapping("/batchOrderAffirmForType")
    public Result batchOrderAffirmForType(@RequestBody OrderApplyAffirm orderApplyAffirmParam) {

        for (OrderApplyAffirm orderApplyAffirm : orderApplyAffirmParam.getOrderApplyAffirmList()) {
            Long orderId = orderApplyAffirm.getOrderId();
            Long disId = orderApplyAffirm.getId();

            OrderApply orderApply = iOrderApplyService.getById(orderId);
            if (orderApply == null) {
                return new Result(Code.ERROR, "", "订单不存在!");
            }

            iOrderApplyAffirmService.addDisAffirm(disId, orderId, 2, 1, "优惠确认", this.adminId);
        }

        return new Result(Code.OK, "", "添加打印记录成功");
    }

}
